﻿///***************************************************************
/// 시  스  템 : Updms.Car
/// 단위시스템 : CAR
/// 계      층 : Presentation Layer
/// 프로그램명 : Car1012m
/// 파  일  명 : Car1012m.aspx.cs
/// 설      명 : 정비관리
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2008-09-01 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.Collections;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using SMFramework.Data;
using SMFramework.Utility;
using SMFramework.Web.UI.WebControls.Page;

using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;
using Updms.Car.Exe;

namespace Updms.Car
{
	public partial class Car1012m : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		//프로그램상수
		public static readonly string PID = "Car1012m";
		public static readonly string gs_path_info = "/updms/Car/" + PID + ".aspx";

		Global global = new Global();
		CommCode.Car car = new CommCode.Car(LANG_SET);

		//페이징
		private int li_cur_page, li_row_count, li_st_page, li_ed_page;
		protected int li_page_size = 10;//GRID_PAGESIZE;// 한 페이지에 출력될 행의수

		//검색
		protected string kw1 = "";	// 차량ID
		protected string kw2 = "";	// 정비구분
		protected string kw3 = "";	// 정비일(~부터)
		protected string kw4 = "";	// 정비일(~까지)

		//메뉴 선택값
		protected string gs_sm = "";

		//페이지별합계
		decimal ld_amount = 0;

		//페이지모드
		private string gs_page_mode = "";	// 팝업으로 열지 여부
		private string gs_service_dt = "";	//정비일
		private string gs_amount = "";		//정비금액
		private string gs_station = "";		//정비소

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
				SearchProcess();
			}
			else
			{
				setScrollLocation();
			}
			SetClientScriptNoPostBack();
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetClientScript();
			SetCarInfoList();
			SetDiv();
			SetCarInfo();
			SetStationId();
			SetSearchParameter();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion

		#region SetClientScript, SetClientScriptNoPostBack, setScrollLocation, get_SetScrollLocation

		private void SetClientScript()
		{
			//onKeyUp이벤트
			txt_amount.Attributes.Add("onkeyup", "document.form1.txt_amount.value=addComma(document.form1.txt_amount.value);");
			txt_distance.Attributes.Add("onkeyup", "document.form1.txt_distance.value=addComma(document.form1.txt_distance.value);");

			//엔터검색
			txt_search_service_dt_from.Attributes.Add("onkeypress", "enterSearchOnPage(event)");
			txt_search_service_dt_to.Attributes.Add("onkeypress", "enterSearchOnPage(event)");

			//달력콘트롤 설정
			ce_service_dt.SelectedDate = string.IsNullOrEmpty(gs_service_dt) ? DateTime.Now.AddDays(0) : Convert.ToDateTime(gs_service_dt);
		}

		//포스트백과 무관하게 이벤트 지정
		private void SetClientScriptNoPostBack()
		{
			//구분
			cbl_search_div.Items[0].Attributes.Add("onclick", "checkBoxListCheck('cbl_search_div');");
		}

		//스크롤바 위치 고정
		protected void setScrollLocation()
		{
			ClientScriptManager cs = this.ClientScript;
			cs.RegisterStartupScript(this.GetType(), "setScroll", get_SetScrollLocation());
		}

		//스크롤바 위치
		public static string get_SetScrollLocation()
		{
			StringBuilder sb = new StringBuilder();

			sb.Append("<script language=javascript>");
			sb.Append("scrollTo();");
			sb.Append("</script>");

			return sb.ToString();
		}

		#endregion

		#region SetInit, SetSearchParameter, ShowKeywordLabel

		//초기값설정
		private void SetInit()
		{
			lbl_search_flag.Text = "INIT";
			if (Request.QueryString["page"] == null || int.Parse(Request.QueryString["page"]) == 1)
			{
				li_cur_page = 1;
				li_st_page = 0;
				li_ed_page = li_page_size;
			}
			else
			{
				li_cur_page = int.Parse(Request.QueryString["page"]);
				li_st_page = (int.Parse(Request.QueryString["page"]) - 1) * li_page_size;
				li_ed_page = li_st_page + li_page_size;
			}

			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();
			gs_page_mode = string.IsNullOrEmpty(Request.QueryString["page_mode"]) ? "" : Request.QueryString["page_mode"].ToString();
			gs_service_dt = string.IsNullOrEmpty(Request.QueryString["service_dt"]) ? "" : Request.QueryString["service_dt"].ToString();
			gs_amount = string.IsNullOrEmpty(Request.QueryString["amount"]) ? "" : Request.QueryString["amount"].ToString();
			gs_station = string.IsNullOrEmpty(Request.QueryString["station"]) ? "" : Request.QueryString["station"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			switch (lbl_search_flag.Text.Trim().ToUpper())
			{
				case "INIT":
					if (String.IsNullOrEmpty(Request.QueryString["kw1"]))	// url에 값이 없으면
					{
						kw1 = ddl_search_car_id.SelectedValue;
					}
					else
					{
						kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
						ddl_search_car_id.SelectedValue = kw1;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw2"]))
					{
						kw2 = WebControlUtil.GetCheckBoxListValue(cbl_search_div, 1);
					}
					else
					{
						kw2 = Server.UrlDecode(Request.QueryString["kw2"]);
						WebControlUtil.SetCheckBoxListValue(cbl_search_div, kw2);
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw3"]))	// url에 값이 없으면
					{
						if (String.IsNullOrEmpty(txt_search_service_dt_from.Text))
						{
							kw3 = DateUtil.GetMonthEx(-12);	// 오늘부터 12개월전
							txt_search_service_dt_from.Text = kw3;
						}
						else
						{
							kw3 = txt_search_service_dt_from.Text.Trim();
						}
					}
					else
					{
						kw2 = Server.UrlDecode(Request.QueryString["kw3"]);
						txt_search_service_dt_from.Text = kw3;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw4"]))	// url에 값이 없으면
					{
						if (String.IsNullOrEmpty(txt_search_service_dt_to.Text))
						{
							kw4 = DateUtil.GetMonthEx(0);	// 오늘
							txt_search_service_dt_to.Text = kw4;
						}
						else
						{
							kw4 = txt_search_service_dt_to.Text.Trim();
						}
					}
					else
					{
						kw4 = Server.UrlDecode(Request.QueryString["kw4"]);
						txt_search_service_dt_to.Text = kw3;
					} break;
				case "SEARCH":
					kw1 = ddl_search_car_id.SelectedValue;
					kw2 = WebControlUtil.GetCheckBoxListValue(cbl_search_div, 1);
					kw3 = String.IsNullOrEmpty(txt_search_service_dt_from.Text) ? DateUtil.GetMonthEx(-12) : txt_search_service_dt_from.Text.Trim();
					kw4 = String.IsNullOrEmpty(txt_search_service_dt_to.Text) ? DateUtil.GetMonthEx(0) : txt_search_service_dt_to.Text.Trim();
					break;
			}
		}

		//검색키워드
		private void ShowKeywordLabel()
		{
			string ls_kw1 = ddl_search_car_id.SelectedItem.Text;
			string ls_kw2 = WebControlUtil.GetCheckBoxListText(cbl_search_div, 1);
			
			lbl_search_keyword.Text = ls_kw1 + " / " + ls_kw2 + " / " + kw3 + " ~ " + kw4;
		}

		#endregion

		#region 마스터 Method (SetCarInfoList, SetCarInfo, SetDiv)

		//차량목록
		private void SetCarInfoList()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			Car1010m_NT _Car1010m_NT = new Car1010m_NT();

			lo_dp.AddProperty("ls_use_yn", typeof(string), "Y");	//사용여부가 Y인것만

			lo_ds.Merge(_Car1010m_NT.GetCarInfoList(lo_dp));

			ddl_search_car_id.Items.Clear();
			ddl_search_car_id.DataSource = lo_ds;
			ddl_search_car_id.DataMember = "UPDMS_CAR_INFO";
			ddl_search_car_id.DataTextField = "Text";
			ddl_search_car_id.DataValueField = "Value";
			ddl_search_car_id.DataBind();
		}

		//차량사진
		private void SetCarInfo()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_car_id", typeof(string), ddl_search_car_id.SelectedValue);

			using (Car1010m_NT _Car1010m_NT = new Car1010m_NT())
			{
				lo_ds.Merge(_Car1010m_NT.GetCarInfo(lo_dp));
			}

			string ls_car_image = DataSetUtil.GetFldStr(lo_ds, "UPDMS_CAR_INFO", "Attach_File1");
			img_car_image.Src = FILE_PATH_UPLOAD_WEB_PATH + (string.IsNullOrEmpty(ls_car_image) ? "empty.png" : ls_car_image);
		}

		//정비구분
		private void SetDiv()
		{
			car.SetDiv(cbl_search_div);
			car.SetDiv(ddl_div);

			cbl_search_div.Items.Insert(0, new ListItem(GetXmlMsg("STR_019"), "ALL"));	//전체선택
		}

		#endregion

		#region 디테일 Method (SetNewServiceId, SetStationId, SetPartHeight, SetCalcTotalAmount, SetExtendRemark)

		//신규서비스아이디
		private void SetNewServiceId()
		{
			Car1012m_NT _Car1012m_NT = new Car1012m_NT();
			lbl_service_id.Text = _Car1012m_NT.GetNewServiceId();
		}

		private void SetStationId()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			Car1013m_NT _Car1013m_NT = new Car1013m_NT();

			lo_dp.AddProperty("ls_div", typeof(string), "AF002");	//정비소
			lo_dp.AddProperty("ls_use_yn", typeof(string), "Y");	//사용여부가 Y인것만
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			lo_ds.Merge(_Car1013m_NT.GetStationListByDiv(lo_dp));
		
			ddl_station_id.Items.Clear();
			ddl_station_id.DataSource = lo_ds;
			ddl_station_id.DataMember = "UPDMS_CAR_STATION";
			ddl_station_id.DataTextField = "Station_Nm";
			ddl_station_id.DataValueField = "Station_Id";
			ddl_station_id.DataBind();
		}

		//부품영역 높이지정
		private void SetPartHeight()
		{
			div_detail_2.Attributes.CssStyle.Remove("height");

			if (cb_part_list_all.Checked)
			{
				int h = (gv_parts.Rows.Count * 23) + 1; //전체 row수 * 하나의 row높이 + 1px
				div_detail_2.Attributes.CssStyle.Add("height", h.ToString() + "px");
			}
			else
			{
				div_detail_2.Attributes.CssStyle.Add("height", "230px");
			}
		}

		//금액 합계
		private void SetCalcTotalAmount()
		{
			decimal ld_calc_amount = 0;

			//선택한 Row의 금액을 계산한다.
			for (int i = 0; i < gv_parts.Rows.Count; i++)
			{
				CheckBox cb_select = (CheckBox)gv_parts.Rows[i].FindControl("cb_select");
				TextBox txt_parts_amount = (TextBox)gv_parts.Rows[i].FindControl("txt_parts_amount");

				if (cb_select.Checked)
				{
					ld_calc_amount = ld_calc_amount + Convert.ToDecimal(ConversionUtil.DefaultValue(txt_parts_amount.Text.Trim(), "0"));
				}
			}

			ltr_calc_total_amount.Text = ld_calc_amount.ToString("#,###,##0");
		}

		//비고높이 재설정(부품 체크박스 클릭시 PostBack후)
		private void SetExtendRemark()
		{
			for (int i = 0; i < gv_parts.Rows.Count; i++)
			{
				CheckBox cb_select = (CheckBox)gv_parts.Rows[i].FindControl("cb_select");
				TextBox txt_parts_remark = (TextBox)gv_parts.Rows[i].FindControl("txt_parts_remark");
				CheckBox cb_parts_remark = (CheckBox)gv_parts.Rows[i].FindControl("cb_parts_remark");

				//S와 비고가 모두 체크되어 있으면 비고의 높이를 80px로 한다
				if (cb_select.Checked && cb_parts_remark.Checked)
				{
					txt_parts_remark.Height = 80;
				}
				else
				{
					txt_parts_remark.Height = 12;
				}
			}
		}

		#endregion		
		
		#region CRUD 부품 (SelectPartsProcess, InsertPartsProcess)

		//조회 - ls_service_id를 안넘기면 부품만 조회해온다
		private void SelectPartsProcess(string ls_service_id)
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			//검색
			lo_dp.AddProperty("ls_service_id", typeof(string), ls_service_id);

			using (Car1012m_NT _Car1012m_NT = new Car1012m_NT())
			{
				lo_ds.Merge(_Car1012m_NT.GetSavedPartsList(lo_dp));
			}

			//일단 바인딩
			gv_parts.DataSource = lo_ds;
			gv_parts.DataBind();

			for (int i = 0; i < DataSetUtil.GetRowCount(lo_ds, "UPDMS_CAR_SERVICE_PARTS"); i++)
			{
				string ls_save_yn = DataSetUtil.GetFldStr(lo_ds, "UPDMS_CAR_SERVICE_PARTS", i, "Save_Yn");
				CheckBox cb_select = (CheckBox)gv_parts.Rows[i].FindControl("cb_select");
				TextBox txt_parts_amount = (TextBox)gv_parts.Rows[i].FindControl("txt_parts_amount");
				TextBox txt_parts_remark = (TextBox)gv_parts.Rows[i].FindControl("txt_parts_remark");
				CheckBox cb_parts_remark = (CheckBox)gv_parts.Rows[i].FindControl("cb_parts_remark");

				//같은 Parts_Id이면 체크함
				if (ls_save_yn == "Y")
				{

					cb_select.Checked = true;
					//어트리뷰트 추가
					string ls_attr =
						"document.form1." + txt_parts_amount.UniqueID + ".value=addComma(document.form1." + txt_parts_amount.UniqueID + ".value);";
					txt_parts_amount.Enabled = true;
					txt_parts_remark.Enabled = true;
					cb_parts_remark.Enabled = true;

					txt_parts_amount.Attributes.Add("onkeyup", ls_attr);
					cb_parts_remark.Attributes.Add("onclick", "extendRemark(\"" + txt_parts_remark.ClientID + "\", \"" + cb_parts_remark.ClientID + "\");");

					//td를 돌면서 어트리뷰트 추가
					for (int j = 0; j < gv_parts.Rows[i].Cells.Count; j++)
					{
						gv_parts.Rows[i].Cells[j].Attributes.Add("class", "bg_white");
					}
				}
				else
				{
					cb_select.Checked = false;
					txt_parts_amount.Text = "";
					txt_parts_remark.Text = "";
					txt_parts_amount.Enabled = false;
					txt_parts_remark.Enabled = false;
					cb_parts_remark.Enabled = false;
					cb_parts_remark.Checked = false;

					//td를 돌면서 어트리뷰트 추가
					for (int j = 0; j < gv_parts.Rows[i].Cells.Count; j++)
					{
						gv_parts.Rows[i].Cells[j].Attributes.Add("class", "bg_gray");
					}
				}
			}
		}

		//저장
		private void InsertPartsProcess()
		{
			using (Car1012m_RT _Car1012m_RT = new Car1012m_RT())
			{
				int li_return = _Car1012m_RT.InsertPartsProcess(SetValueParts());
			}
		}

		#endregion

		#region CRUD (SelectProcess, InsertProcess, UpdateProcess, DeleteProcess, SearchProcess)

		//조회
		private void SelectProcess()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			int li_page_count;

			//검색
			lo_dp.AddProperty("ls_car_id", typeof(string), kw1);
			lo_dp.AddProperty("ls_div", typeof(string), kw2);
			lo_dp.AddProperty("ls_service_dt_from", typeof(string), kw3);
			lo_dp.AddProperty("ls_service_dt_to", typeof(string), kw4);

			using (Car1012m_NT _Car1012m_NT = new Car1012m_NT())
			{
				li_row_count = _Car1012m_NT.GetSearchCount(lo_dp);	// 검색된 행수
				li_page_count = (int)((li_row_count - 1) / li_page_size) + 1;	// 총페이지수 계산

				//모두보기/페이징
				lo_dp.AddProperty("li_st_page", typeof(Int32), (cb_list_all.Checked) ? 0 : li_st_page);
				lo_dp.AddProperty("li_ed_page", typeof(Int32), (cb_list_all.Checked) ? li_row_count : li_ed_page);
				lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);
				lbl_page.Visible = !cb_list_all.Checked;

				lo_ds.Merge(_Car1012m_NT.SelectProcess(lo_dp));
			}

			GridView1.DataSource = lo_ds;
			GridView1.DataBind();

			Pager pager = new Pager(this, ref lbl_page);
			pager.PageNavigation(
				li_cur_page,
				li_page_count,
				gs_path_info + "?sm=" + gs_sm + "&kw1=" + Server.UrlEncode(kw1) + "&kw2=" + Server.UrlEncode(kw2) + "&kw3=" + Server.UrlEncode(kw3) + "&kw4=" + Server.UrlEncode(kw4) + "&page_mode=" + gs_page_mode + "&page=");

			//결과출력(키워드, 검색행수)
			ShowKeywordLabel();
			lbl_result_count.Text = li_row_count.ToString("#,###,##0");
		}

		//저장
		private void InsertProcess()
		{
			using (Car1012m_RT _Car1012m_RT = new Car1012m_RT())
			{
				int li_return = _Car1012m_RT.InsertProcess(SetValue());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_007" : "MSG_ERR_105";	//저장되었습니다:저장할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//수정
		private void UpdateProcess()
		{
			using (Car1012m_RT _Car1012m_RT = new Car1012m_RT())
			{
				int li_return = _Car1012m_RT.UpdateProcess(SetValue());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_006" : "MSG_ERR_104";	//수정되었습니다:수정할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//삭제
		private void DeleteProcess(string ls_xml)
		{
			using (Car1012m_RT _Car1012m_RT = new Car1012m_RT())
			{
				int li_return = _Car1012m_RT.DeleteProcess(ls_xml);
				string ls_msg_id = (li_return > 0) ? "MSG_INF_004" : "MSG_ERR_103";	//삭제되었습니다:삭제할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//검색
		private void SearchProcess()
		{
			lbl_search_flag.Text = "SEARCH";
			SetSearchParameter();
			ClearValue();
			SelectProcess();
			SelectPartsProcess("");
			SetNewServiceId();
		}

		#endregion		

		#region SetValue, ClearValue, SetValueParts

		//SetValue
		private DataPack SetValue()
		{
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("Seq",				typeof(string),		lbl_pk.Text);
			lo_dp.AddProperty("Car_Id",				typeof(string), 	ddl_search_car_id.SelectedValue);
			lo_dp.AddProperty("Service_Id",			typeof(string),		lbl_service_id.Text);
			lo_dp.AddProperty("Div",				typeof(string), 	ddl_div.SelectedValue);
			lo_dp.AddProperty("Service_Dt",			typeof(string), 	ConversionUtil.DefaultValue(txt_service_dt.Text));
			lo_dp.AddProperty("Station_Id",			typeof(string), 	ddl_station_id.SelectedValue);
			lo_dp.AddProperty("Contents",			typeof(string), 	ConversionUtil.DefaultValue(txt_contents.Text));
			lo_dp.AddProperty("Amount",				typeof(string), 	ConversionUtil.ExtractNumberStr(ConversionUtil.DefaultValue(txt_amount.Text,"0")));
			lo_dp.AddProperty("Distance",			typeof(string), 	ConversionUtil.ExtractNumberStr(ConversionUtil.DefaultValue(txt_distance.Text,"0")));
			lo_dp.AddProperty("Remark",				typeof(string), 	ConversionUtil.DefaultValue(txt_remark.Text));
			lo_dp.AddProperty("Create_User",		typeof(string), 	USER_ID);
			lo_dp.AddProperty("Create_Dt",			typeof(string), 	"");
			lo_dp.AddProperty("Update_User",		typeof(string), 	USER_ID);
			lo_dp.AddProperty("Update_Dt",			typeof(string), 	"");

			return lo_dp;
		}

		//ClearValue
		private void ClearValue()
		{
			lbl_pk.Text = "";
			h_no.Value = "";
			lbl_service_id.Text = "";
			ddl_div.SelectedIndex = 0;
			ce_service_dt.SelectedDate = DateTime.Now.AddDays(0);
			ddl_station_id.SelectedIndex = 0;
			txt_contents.Text = "";
			txt_amount.Text = "";
			txt_distance.Text = "";
			txt_remark.Text = "";	
		}
		
		//부품 - xml로 저장 및 수정
		private string SetValueParts()
		{
			StringBuilder sb = new StringBuilder();		

			sb.Append("<UPDMS>");

			//루프를 돌면서 선택된 데이터만 XML로 만듬
			for (int i = 0; i < gv_parts.Rows.Count; i++)
			{
				CheckBox cb_select = (CheckBox)gv_parts.Rows[i].FindControl("cb_select");
				string ls_seq = gv_parts.DataKeys[i].Values["Seq"].ToString();
				TextBox txt_parts_amount = (TextBox)gv_parts.Rows[i].FindControl("txt_parts_amount");
				TextBox txt_parts_remark = (TextBox)gv_parts.Rows[i].FindControl("txt_parts_remark");
				string ls_save_yn = gv_parts.DataKeys[i].Values["Save_Yn"].ToString();

				if (cb_select.Checked)
				{
					sb.Append("<UPDMS_CAR_SERVICE_PARTS>");
					sb.Append("<Seq>" + ls_seq + "</Seq>");
					sb.Append("<Save_Yn>" + ls_save_yn + "</Save_Yn>");	//실제 저장되는 값은 아님
					sb.Append("<Car_Id>" + ddl_search_car_id.SelectedValue + "</Car_Id>");
					sb.Append("<Service_Dt>" + txt_service_dt.Text + "</Service_Dt>");
					sb.Append("<Service_Id>" + lbl_service_id.Text + "</Service_Id>");
					sb.Append("<Parts_Id>" + gv_parts.Rows[i].Cells[3].Text + "</Parts_Id>");
					sb.Append("<Amount>" + ConversionUtil.ExtractNumberInt(ConversionUtil.DefaultValue(txt_parts_amount.Text, "0")) + "</Amount>");
					sb.Append("<Distance>" + ConversionUtil.ExtractNumberStr(ConversionUtil.DefaultValue(txt_distance.Text, "0")) + "</Distance>");
					sb.Append("<Remark>" + ConversionUtil.DefaultValue(txt_parts_remark.Text) + "</Remark>");
					sb.Append("<Create_User>" + USER_ID + "</Create_User>");
					sb.Append("<Create_Dt></Create_Dt>");
					sb.Append("<Update_User>" + USER_ID + "</Update_User>");
					sb.Append("<Update_Dt></Update_Dt>");
					sb.Append("</UPDMS_CAR_SERVICE_PARTS>");
				}
				else if (ls_save_yn == "Y")
				{
					//언체크항목중 Save_Yn이 Y 이면 삭제할 대상이다. Save_Yn을 하이픈(-)으로 넘겨서 삭제한다.
					sb.Append("<UPDMS_CAR_SERVICE_PARTS>");
					sb.Append("<Seq>" + ls_seq + "</Seq>");
					sb.Append("<Save_Yn>-</Save_Yn>");
					sb.Append("</UPDMS_CAR_SERVICE_PARTS>");
				}
			}
			
			sb.Append("</UPDMS>");

			//Base.AppFramework.SMEventLog.WriteDataLog("SetValueParts()", sb.ToString());
			
			return sb.ToString();
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
					//사용권한별 버튼처리
					PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
				}
			}
			ChangePageMode();
		}


		//ChangePageMode
		private void ChangePageMode()
		{
			switch (gs_page_mode)
			{
				case "":		// 처음 페이지로드시
					Top.Visible = true;
					menu_area.Attributes.Add("class", "");
					ibtn_close.Visible = false;
					break;
				case "P":	// 팝업으로 열때
					Top.Visible = false;
					menu_area.Attributes.Add("class", "nodisplay");
					ce_service_dt.SelectedDate
						= string.IsNullOrEmpty(gs_service_dt) ? DateTime.Now.AddDays(0) : Convert.ToDateTime(gs_service_dt);
					txt_amount.Text = gs_amount;
					
					if (WebControlUtil.CheckDdlText(ddl_station_id, gs_station))
					{
						ddl_station_id.SelectedValue = WebControlUtil.GetDdlValueByText(ddl_station_id, gs_station);
					}

					ibtn_close.Visible = true;
					break;
			}
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}
		#endregion

		#region GridView이벤트

		//RowDataBound
		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onmouseover", "overBackground('GridView1', " + (e.Row.RowIndex + 1) + ")");
				e.Row.Attributes.Add("onmouseout", "outBackground('GridView1', 1)");

				//번호
				e.Row.Cells[1].Text	= cb_list_all.Checked
					? (li_row_count - e.Row.RowIndex).ToString() 
					: ((li_row_count - ((li_cur_page - 1) * li_page_size)) - e.Row.RowIndex).ToString();

				//페이지별 합계
				ld_amount += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Amount"));
			}

			//Footer에 합계 바인딩
			if (e.Row.RowType == DataControlRowType.Footer)
			{
				e.Row.Cells[0].Text = "Total";
				e.Row.Cells[0].Attributes.Add("class", "total");
				e.Row.Cells[0].ColumnSpan = 8;
				e.Row.Cells[1].Visible = false;
				e.Row.Cells[2].Visible = false;
				e.Row.Cells[3].Visible = false;
				e.Row.Cells[4].Visible = false;
				e.Row.Cells[5].Visible = false;
				e.Row.Cells[6].Visible = false;
				e.Row.Cells[7].Visible = false;
				e.Row.Cells[8].Visible = false;
				e.Row.Cells[9].Visible = false;
				e.Row.Cells[10].Visible = false;
				e.Row.Cells[11].Visible = false;
				e.Row.Cells[12].Text = ld_amount.ToString("#,###,##0");
				e.Row.Cells[12].Attributes.Add("class", "money");
				e.Row.Cells[13].Text = "";
				e.Row.Cells[13].Attributes.Add("class", "none");
				e.Row.Cells[14].Visible = false;
			}
		}

		//RowCommand
		protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			GridView gv = (GridView)sender;
			GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);

			LinkButton lbtn_rc = (LinkButton)GridView1.Rows[row.RowIndex].FindControl("lbtn_rc");

			//row.Cells[0].Text.ToString();//0.체크박스
			h_no.Value						= row.Cells[1].Text.ToString();//1.번호
			lbl_pk.Text						= gv.DataKeys[row.RowIndex].Values["Seq"].ToString();			//2.Seq
			ddl_search_car_id.SelectedValue	= gv.DataKeys[row.RowIndex].Values["Car_Id"].ToString();		//3.Car_Id
																											//4.Car_Nm
			lbl_service_id.Text				= gv.DataKeys[row.RowIndex].Values["Service_Id"].ToString();	//5.Service_Id
			ddl_div.SelectedValue			= gv.DataKeys[row.RowIndex].Values["Div"].ToString();			//6.Div
																											//7.Div_Nm
			txt_service_dt.Text				= lbtn_rc.Text;													//8.Service_Dt (template)
			ddl_station_id.SelectedValue	= gv.DataKeys[row.RowIndex].Values["Station_Id"].ToString();	//9.Station_Id
																											//10.Station_Nm
																											//11.Whereis_Url_Link
			txt_contents.Text				= row.Cells[12].Text.Trim();									//12.Contents
			txt_amount.Text					= row.Cells[13].Text.Trim();									//13.Amount
			txt_distance.Text				= row.Cells[14].Text.Trim();									//14.Distance
			txt_remark.Text					= gv.DataKeys[row.RowIndex].Values["Remark"].ToString();		//15.Remark
			
			//저장된 부품리스트 조회
			SelectPartsProcess(lbl_service_id.Text);
			SetCalcTotalAmount();
			SetPartHeight();
		}

		//RowDataBound
		protected void gv_parts_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onMouseOver", GRID_ONMOUSEOVER_COLOR);
				e.Row.Attributes.Add("onMouseOut", GRID_ONMOUSEOUT_COLOR);
			}
		}

		#endregion

		#region 버튼이벤트

		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//저장
		protected void ibtn_save_Click(object sender, EventArgs e)
		{
			//부품은 무조건 저장
			InsertPartsProcess();
			
			if (global.CheckSaveMode("UPDMS_CAR_SERVICE", "Seq", lbl_pk.Text.Trim()))
			{
				UpdateProcess();
			}
			else
			{
				InsertProcess();
			}
		}

		//삭제
		protected void ibtn_delete_Click(object sender, EventArgs e)
		{
			StringBuilder sb = new StringBuilder();

			sb.Append("<UPDMS>");

			for (int i = 0; i < GridView1.Rows.Count; i++)
			{
				GridViewRow row = GridView1.Rows[i];
				HtmlInputCheckBox cb = (HtmlInputCheckBox)row.FindControl("cb_check");

				if (cb.Checked)
				{
					string ls_seq = GridView1.DataKeys[i].Values["Seq"].ToString();
					sb.Append("<UPDMS_CAR_SERVICE>");
					sb.Append("<Seq>" + ls_seq + "</Seq>");
					sb.Append("</UPDMS_CAR_SERVICE>");
				}
			}
			sb.Append("</UPDMS>");

			DeleteProcess(sb.ToString());
		}

		//엑셀
		protected void ibtn_excel_Click(object sender, EventArgs e)
		{
			SetSearchParameter();

			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_car_id", typeof(string), kw1);
			lo_dp.AddProperty("ls_div", typeof(string), kw2);
			lo_dp.AddProperty("ls_service_dt_from", typeof(string), kw3);
			lo_dp.AddProperty("ls_service_dt_to", typeof(string), kw4);

			using (Car1012m_NT _Car1012m_NT = new Car1012m_NT())
			{
				li_row_count = _Car1012m_NT.GetSearchCount(lo_dp);

				lo_dp.AddProperty("li_st_page", typeof(Int32), 0);
				lo_dp.AddProperty("li_ed_page", typeof(Int32), li_row_count);
				lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

				lo_ds.Merge(_Car1012m_NT.SelectProcess(lo_dp));
			}
			string fileName = PID + "(" + global.GetMenuTitle(PID, LANG_SET) + ")";
			ExcelUtil.CreateExcelFileX(this.Page, fileName, lo_ds, SetExcelHeaderX(global.GetColumnListByPgmId(PID, LANG_SET)));
		}

		//모두보기
		protected void cb_list_all_CheckedChanged(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//부품목록에서 체크박스선택시
		protected void cb_select_CheckedChanged(object sender, EventArgs e)
		{
			GridViewRow gvr = ((GridViewRow)((Control)sender).Parent.Parent);
			int checked_row_index = gvr.RowIndex;

			//선택한 Row의 금액,비고를 활성화 한다.
			CheckBox cb_select = (CheckBox)gv_parts.Rows[checked_row_index].FindControl("cb_select");
			TextBox txt_parts_amount = (TextBox)gv_parts.Rows[checked_row_index].FindControl("txt_parts_amount");
			TextBox txt_parts_remark = (TextBox)gv_parts.Rows[checked_row_index].FindControl("txt_parts_remark");
			CheckBox cb_parts_remark = (CheckBox)gv_parts.Rows[checked_row_index].FindControl("cb_parts_remark");

			if (cb_select.Checked)
			{
				//어트리뷰트 추가
				string ls_attr =
					"document.form1." + txt_parts_amount.UniqueID + ".value=addComma(document.form1." + txt_parts_amount.UniqueID + ".value);";
				txt_parts_amount.Enabled = true;
				txt_parts_remark.Enabled = true;
				cb_parts_remark.Enabled = true;

				txt_parts_amount.Attributes.Add("onkeyup", ls_attr);
				cb_parts_remark.Attributes.Add("onclick", "extendRemark(\"" + txt_parts_remark.ClientID + "\", \"" + cb_parts_remark.ClientID + "\");");

				//td를 돌면서 어트리뷰트 추가
				for (int j = 0; j < gv_parts.Rows[checked_row_index].Cells.Count; j++)
				{
					gv_parts.Rows[checked_row_index].Cells[j].Attributes.Add("class", "bg_white");
				}
			}
			else
			{
				txt_parts_amount.Text = "";
				txt_parts_remark.Text = "";
				txt_parts_amount.Enabled = false;
				txt_parts_remark.Enabled = false;
				cb_parts_remark.Enabled = false;
				cb_parts_remark.Checked = false;

				//td를 돌면서 어트리뷰트 추가
				for (int j = 0; j < gv_parts.Rows[checked_row_index].Cells.Count; j++)
				{
					gv_parts.Rows[checked_row_index].Cells[j].Attributes.Add("class", "bg_gray");
				}
			}

			//비고높이 재설정
			SetExtendRemark();
		}

		//부품 모두보기
		protected void cb_part_list_all_CheckedChanged(object sender, EventArgs e)
		{
			SetPartHeight();
			SetExtendRemark();
		}

		//금액합계계산
		protected void lbtn_calc_total_amount_Click(object sender, EventArgs e)
		{
			SetCalcTotalAmount();
		}

		#endregion		
	}
}
